import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_collection.dart';
import 'package:tender_flutter/page/home/item/tender_list_cell.dart';
import 'package:tender_flutter/page/home/model/tender_entity.dart';
import 'package:tender_flutter/page/subscription/api/api_subscription.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

class SubscriptionListPage extends StatefulWidget {
  /// 订阅分组ID
  final int subscriptionId;

  /// 订阅的关键词
  final List<String> keywords;

  const SubscriptionListPage({Key key, this.subscriptionId, this.keywords})
      : super(key: key);

  @override
  _SubscriptionPageState createState() => _SubscriptionPageState();
}

class _SubscriptionPageState extends State<SubscriptionListPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<TenderEntity>> _future;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  List<TenderList> _dataLists = [];

  ///下拉刷新
  void _onRefresh() {
    page = 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 收藏/取消
  /// 返回是否请求成功的状态
  Future<bool> _setCollection({int tenderId}) async {
    var response = await ApiCollection.tenderCollection(tenderId: tenderId);
    ToastUtils.show(response.msg);
    return response.status == Status.SUCCESS ? true : false;
  }

  /// 获取数据
  Future<ApiResponse<TenderEntity>> _getData() async {
    var response = await ApiSubscription.subscriptionTenderList<TenderEntity>(
      id: widget.subscriptionId,
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  FutureBuilder<ApiResponse<TenderEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<TenderEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              TenderEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted(resetFooterState: true);
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _future = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
        context,
        Text(
          "订阅信息",
          style: FonStyle.navTextStyle(),
        ));
  }

  /// 内容体
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            TenderList model = _dataLists[index];
            return TenderListCell(
                data: model,
                highlightWords: widget.keywords,
                onCollection: () async {
                  return await _setCollection(tenderId: model.id);
                },
                onTap: () {
                  LRouter.navigatorCtx(context).push(Routes.tenderDetailPage,
                      queryParams: {"tenderId": model.id.toString()});
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType49,
            );
          },
        ));
  }
}
